/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * PmTaskLogController 任务工作日志
 * <p>
 * 修改纪录 2020-05-15 版本：1.0 wushenghong 创建。
 *
 * @version 版本：1.0
 * @author 作者：wushenghong 创建日期：2020-05-15
 */

package com.topscomm.pm.controller;

import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.CboSystemConst;
import com.topscomm.pm.controller.auto.PmTaskLogControllerAuto;
import com.topscomm.pm.pojo.PmProjectEntity;
import com.topscomm.pm.pojo.PmTaskEntity;
import com.topscomm.pm.pojo.PmTaskLogEntity;
import com.topscomm.pm.service.impl.PmCalendarService;
import com.topscomm.pm.service.impl.PmProjectService;
import com.topscomm.pm.service.impl.PmTaskService;
import com.topscomm.pm.utils.MisStringUtil;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.common.TapSystemConst;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: wushenghong
 * @date: 2020-05-15
 * @description:任务工作日志Controller
 * @modify:
 */
@RestController
@RequestMapping("pm/taskLog")
public class PmTaskLogController extends PmTaskLogControllerAuto
        implements IPmTaskLogController {
    /**
     * @param paraMap
     * @return
     * @author: wushenghong
     * @date: 2020-05-15
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" PmTaskLog.enabled=1 ");
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.state={0}", value);
        }
        if (paraMap.containsKey("qry_user")) {
            String value = paraMap.get("qry_user").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.username like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_taskname")) {
            String value = paraMap.get("qry_taskname").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.name like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_username")) {
            String value = paraMap.get("qry_username").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.username like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_name")) {
            String value = paraMap.get("qry_name").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.name like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_docno")) {
            String value = paraMap.get("qry_docno").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.docno like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.finishtime >= {0} ",
                        SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.finishtime <= {0}",
                        SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.projectid={0}", value);
        }
        /*
         * if (paraMap.containsKey("qry_deptname")) { String value =
         * paraMap.get("qry_deptname").toString(); if
         * (!StringUtil.isEmpty(value)) sql.
         * appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))"
         * , value); }
         */
        if (paraMap.containsKey("qry_user")) {
            String value = paraMap.get("qry_user").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (PmTaskLog.username like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_deptcode")) {
            String value = paraMap.get("qry_deptcode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.deptcode = '{0}'", value);
        }
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.state={0}", value);
        }
        if (paraMap.containsKey("qry_userStr")) {
            String value = paraMap.get("qry_userStr").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (PmTaskLog.usercode='{0}' or PmTaskLog.username like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_where")) {
            String value = paraMap.get("qry_where").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and {0}", value);
        }
        sql .appendSingle(this.spellingSqlForProject(paraMap, "PmTaskLog","projectid","id"));
        if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
        {
            String dataPession = service.getDataPermission(
                    TapSystemConst.TapOperationTypeEnum.Select, "",
                    this.getUserBean());
            if (StringUtil.isEmpty(dataPession)) {
                sql.appendSingle(" and (" + MisStringUtil.createWhereByUsercodeFromProject(
                        this.getUserBean().getUser(), "projectid",
                        service.getDao().getTableName()) + " or PmTaskLog.usercode = '{0}')", this.getUserBean().getUser().getCode());
            } else// 使用数据权限
            {
                sql.appendSingle(" and {0} ", dataPession);
            }
        }
        return sql.toString();
    }

    /**
     * @param paraMap
     * @return
     * @author: wushenghong
     * @date: 2020-05-15
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        return super.refList(paraMap);
    }

    /**
     * @param dataMap
     * @param paraMap
     * @throws Exception
     * @description: 提交审批前
     * @author: wushenghong
     * @date: 2020-05-15
     * @modify:
     */
    @Override
    protected void beforeSubmit(Map<String, Object> dataMap,
                                Map<String, Object> paraMap) throws Exception {
        super.beforeSubmit(dataMap, paraMap);
        StringBufferProxy mailtitle = new StringBufferProxy();
        mailtitle.appendSingle("{0}{1}于{2}提交任务工作日志申请,单据编号{3}! ",
                dataMap.get("dispdeptcode"), dataMap.get("username"),
                DateUtil.dateToString(new Date(), "yyyy-MM-dd"),
                dataMap.get("docno"));
        dataMap.put("maintitle", mailtitle.toString());
        List<Map<String, Object>> flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_PmTaskLog", dataMap.get("deptcode").toString(), dataMap.get("usercode").toString(), null, "sortcode");
        Long flowid = flowidList.size() > 0 ? ConvertUtil.convertToLong(flowidList.get(0).get("id")) : null;
        dataMap.put("flowid", flowid);
    }

    protected String spellListSqlStatistics(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" PmTaskLog.enabled=1 ");
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.state={0}", value);
        }
        if (paraMap.containsKey("qry_user")) {
            String value = paraMap.get("qry_user").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (PmTaskLog.username like '%{0}%' or PmTaskLog.usercode like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_contractname")) {
            String value = paraMap.get("qry_contractname").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and contractname like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_username")) {
            String value = paraMap.get("qry_username").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.username like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_name")) {
            String value = paraMap.get("qry_name").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.name like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_docno")) {
            String value = paraMap.get("qry_docno").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.docno like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.finishtime >= {0} ",
                        SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.finishtime <= {0}",
                        SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.projectid={0}", value);
        }
        if (paraMap.containsKey("qry_username")) {
            String value = paraMap.get("qry_username").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (PmTaskLog.username like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_deptcode")) {
            String value = paraMap.get("qry_deptcode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and deptcode like '{0}%'", value);
        }
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.state={0}", value);
        }
        if (paraMap.containsKey("qry_where")) {
            String value = paraMap.get("qry_where").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and {0}", value);
        }
        if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
        {
            String dataPession = service.getDataPermission(
                    TapSystemConst.TapOperationTypeEnum.Select, "",
                    this.getUserBean());
            if (StringUtil.isEmpty(dataPession))// 默认权限只能看本人，部门负责人为自己的部门和下级部门的数据
            {
//                sql.appendSingle(" and (" + MisStringUtil.createWhereByUsercodeFromProject(
//                    this.getUserBean().getUser(), "projectid",
//                    service.getDao().getTableName()) + " or usercode = '{0}')", this.getUserBean().getUser().getCode());
            } else// 使用数据权限
            {
                sql.appendSingle(" and {0} ", dataPession);
            }
        }
        return sql.toString();

    }

    //=========================任务查询相关====================================================================================================

    protected String spellListSqlStatisticsOther(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" PmTaskLog.enabled=1 ");
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and projectid={0}", value);
        }
        if (paraMap.containsKey("qry_username")) {
            String value = paraMap.get("qry_username").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (username like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_usercode")) {
            String value = paraMap.get("qry_usercode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and usercode = '{0}'", value);
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.finishtime >= {0} ",
                        SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.finishtime <= {0}",
                        SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and PmTaskLog.state={0}", value);
        }
        return sql.toString();
    }

    @GetMapping({"/listStatistics"})
    public ResponseResult<Object> listStatistics(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSqlStatisticsOther(paraMap);
            int totalCount = ((ITapService) this.service).getCount(sqlWhere);
            List<Map<String, Object>> tempList = null;
            if (query.getPageSize() > 0) {
                tempList = ((ITapService) this.service).queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
            } else {
                tempList = ((ITapService) this.service).queryMapByWhere(sqlWhere);
            }

            ((ITapService) this.service).setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }

    //=========================任务查询相关结束====================================================================================================

    /**
     * @param paraMap
     * @return
     * @author: wushenghong
     * @date: 2020-07-20
     * @description:当日时间占比校验并更新
     * @modify:
     */
    @PutMapping(value = "/updateLog")
    public ResponseResult<Object> updateLog(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            String id = ConvertUtil.convertToString(paraMap.get("id"));
            // 当前日志的时间占比
            BigDecimal timeProportionAll = ConvertUtil.convertToBigDecimal(paraMap.get("timetroportion"));
            PmTaskLogEntity pmTaskLogEntity = this.service.queryById(id);
            StringBufferProxy sql = new StringBufferProxy();
            if (pmTaskLogEntity != null) {
                // 日志填写和审批不通过再次提交的需要检验填写的时间占比
                if("日志填写".equals(pmTaskLogEntity.getLatestphase())||"审批不通过,已退回".equals(pmTaskLogEntity.getLatestphase())){
                    sql.appendSingle("select  sum(NVL(TIMETROPORTION,0)) as TIMETROPORTIONNUM from PMTASKLOG where USERCODE='{0}' and DOCDATE ={1} and id<>'{2}' and (state='9' or latestphase='项目经理审批')",pmTaskLogEntity.getUsercode(),
                        SQLAdapter.toDateLong(pmTaskLogEntity.getValue("docdate").toString()),pmTaskLogEntity.getId());
                    List<Map<String, Object>> maps = this.service.selectExecute(sql.toString());
                    if(maps.size()>0){
                        BigDecimal timetroportionnum = ConvertUtil.convertToBigDecimal(maps.get(0).get("timetroportionnum"));
                        BigDecimal time = ConvertUtil.convertToBigDecimal(paraMap.get("timetroportion"));
                        BigDecimal addnum = timetroportionnum.add(time);
                        if(addnum.subtract(new BigDecimal("1.0")).compareTo(BigDecimal.ZERO)>0){
                            throw new MessageException("该日期总的时间占比之和超过1，请重新填写！");
                        }
                    }
                }
                String usercode = pmTaskLogEntity.getUsercode();
                String finishTime = cn.hutool.core.date.DateUtil.formatDate(pmTaskLogEntity.getFinishtime());
                sql.clear();
                sql.appendSingle("select sum(NVL(timetroportion,0)) as timeproportionall from PmTaskLog where finishtime = {0} and state = 9 and usercode = '{1}'", SQLAdapter.toDateLong(finishTime + " 00:00:00"), usercode);
                List<Map<String, Object>> timeProportionList = this.service.selectExecute(sql.toString());
                if (timeProportionList.size() > 0) {
                    BigDecimal partTimeProportionAll = ConvertUtil.convertToBigDecimal(timeProportionList.get(0).get("timeproportionall"));
                    timeProportionAll = timeProportionAll.add(partTimeProportionAll);
                }
            }
            if (timeProportionAll.compareTo(BigDecimal.valueOf(1.0)) > 0) {
                return ResponseResult.error("当日填写日志的时间占比之和为" + timeProportionAll + "，已超过1，请重新填写！");
            } else {
                this.service.update(paraMap);
                return ResponseResult.ok("修改成功");
            }
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @param paraMap
     * @return
     * @description:查询列表
     * @author: sunxl
     * @date:
     * @modify:
     */
    @GetMapping(value = "/projectStatistics")
    public ResponseResult<Object> projectList(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSqlStatistics(paraMap);
            sqlWhere = sqlWhere + " and state=9";
            int totalCount = this.service.getCountStatistics(sqlWhere,
                    "getCountProject");
            List<Map<String, Object>> tempList = null;

            if (query.getPageSize() > 0) {
                tempList = this.service.queryMapForPageStatistics(sqlWhere,
                        query.getCurrentPage(), query.getPageSize(),
                        query.getSidx(), query.getSord(),
                        "queryMapForPageProject");
            } else {
                StringBufferProxy sql = new StringBufferProxy();
                sql.appendSingle(sqlWhere);
                sql.appendSingle(" GROUP BY projectid ");
                tempList = this.service.queryMapByWhereStatistics(
                        sql.toString(), "queryMapByWhereProject");
            }

            this.service.setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(),
                    query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @param paraMap
     * @return
     * @description:查询列表
     * @author: sunxl
     * @date:
     * @modify:
     */
    @GetMapping(value = "/deptStatistics")
    public ResponseResult<Object> deptList(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSqlStatistics(paraMap) + " and state = 9";
            int totalCount = this.service.getCountStatistics(sqlWhere,
                    "getCountDept");
            List<Map<String, Object>> tempList = null;

            if (query.getPageSize() > 0) {
                tempList = this.service.queryMapForPageStatistics(sqlWhere,
                        query.getCurrentPage(), query.getPageSize(),
                        query.getSidx(), query.getSord(),
                        "queryMapForPageDept");
            } else {
                StringBufferProxy sql = new StringBufferProxy();
                sql.appendSingle(sqlWhere);
                sql.appendSingle("  GROUP BY deptcode,deptname ");
                tempList = this.service.queryMapByWhereStatistics(
                        sql.toString(), "queryMapByWhereDept");
            }
            // 部门增加上下级关系  统计数据进行汇总
            if (tempList.size() > 0) {
                for (Map<String, Object> list : tempList) {
                    String deptCode = ConvertUtil.convertToString(list.get("deptcode"));
                    StringBufferProxy sql = new StringBufferProxy();
                    sql.appendSingle("  select sum(NVL(timetroportion,0)) as num from PmTaskLog where state = 9  and deptcode like '{0}%'", deptCode);
                    List<Map<String, Object>> numList = this.service.selectExecute(sql.toString());
                    BigDecimal num = ConvertUtil.convertToBigDecimal(numList.get(0).get("num"));
                    list.put("num", num);
                }
            }
            Page page = new Page(tempList, totalCount, query.getPageSize(),
                    query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @param paraMap
     * @return
     * @description:查询列表
     * @author: sunxl
     * @date:
     * @modify:
     */
    @GetMapping(value = "/personStatistics")
    public ResponseResult<Object> personList(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSqlStatistics(paraMap);
            sqlWhere = " state = 9 and " + sqlWhere;
            int totalCount = this.service.getCountStatistics(sqlWhere,
                    "getCountPerson");
            List<Map<String, Object>> tempList = null;

            if (query.getPageSize() > 0) {
                tempList = this.service.queryMapForPageStatistics(sqlWhere,
                        query.getCurrentPage(), query.getPageSize(),
                        query.getSidx(), query.getSord(),
                        "queryMapForPagePerson");
            } else {
                StringBufferProxy sql = new StringBufferProxy();
                sql.appendSingle(sqlWhere);
                sql.appendSingle(" GROUP BY usercode,username,projectid ");
                tempList = this.service.queryMapByWhereStatistics(
                        sql.toString(), "queryMapByWherePerson");
            }
            this.service.setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(),
                    query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @param paraMap
     * @return
     * @description:
     * @author: sunxl
     * @date: 2020-05-26
     * @modify:
     */
    @PostMapping(value = "/exportTaskLogProjectExcel")
    public void exportExcelProject(
            @RequestBody(required = false) Map<String, Object> paraMap,
            HttpServletRequest request, HttpServletResponse response) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
            String sord = ConvertUtil.convertToString(paraMap.get("sord"));
            String cols = ConvertUtil.convertToString(paraMap.get("cols"));
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(spellListSqlStatistics(paraMap));
            // modify by wushenghong  导出数据与查询数据不对应问题解决
            sql.appendSingle(" and state = 9 ");
            sql.appendSingle(" GROUP BY projectid ");
            if (!StringUtil.isEmpty(sidx) && !StringUtil.isEmpty(sord)) {
                sql.appendSingle(" order by {0} {1} ", sidx, sord);
            }
            List<Map<String, Object>> listDataMap = this.service
                    .queryMapByWhereStatistics(sql.toString(),
                            "queryMapByWhereProject");
            for (int i = 0; i < listDataMap.size(); i++) {
                Map<String, Object> groupInfoList = listDataMap.get(i);
                if (groupInfoList != null) {
                    groupInfoList.put("projectid",
                            listDataMap.get(i).get("projectid").toString());
                }
            }
            String[] colArray = cols.split(",");
            InputStream inStream = OfficeOperateUtil
                    .exportExeclXlsx(listDataMap, colArray);
            String fileName = "导出数据.xlsx";
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + fileName);
            response.setHeader("FileName",
                    URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "FileName");
            OutputStream outStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while ((len = inStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            inStream.close();
        } catch (Exception ex) {
            throw new BusinessException(ex.getMessage(), true);
        }
    }

    /**
     * @param paraMap
     * @return
     * @description:
     * @author: sunxl
     * @date: 2020-05-26
     * @modify:
     */
    @PostMapping(value = "/exportTaskLogDeptExcel")
    public void exportExcelDept(
            @RequestBody(required = false) Map<String, Object> paraMap,
            HttpServletRequest request, HttpServletResponse response) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
            String sord = ConvertUtil.convertToString(paraMap.get("sord"));
            String cols = ConvertUtil.convertToString(paraMap.get("cols"));
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(spellListSqlStatistics(paraMap));
            // modify by wushenghong  导出数据与查询数据不对应问题解决
            sql.appendSingle(" and state = 9 ");
            sql.appendSingle(" GROUP BY deptcode,deptname ");
            if (!StringUtil.isEmpty(sidx) && !StringUtil.isEmpty(sord)) {
                sql.appendSingle(" order by {0} {1} ", sidx, sord);
            }
            List<Map<String, Object>> listDataMap = this.service
                    .queryMapByWhereStatistics(sql.toString(),
                            "queryMapByWhereDept");
            for (int i = 0; i < listDataMap.size(); i++) {
                Map<String, Object> groupInfoList = listDataMap.get(i);
                if (groupInfoList != null) {
                    groupInfoList.put("deptcode",
                            listDataMap.get(i).get("deptcode").toString());
                }
            }
            String[] colArray = cols.split(",");
            InputStream inStream = OfficeOperateUtil
                    .exportExeclXlsx(listDataMap, colArray);
            String fileName = "导出数据.xlsx";
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + fileName);
            response.setHeader("FileName",
                    URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "FileName");
            OutputStream outStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while ((len = inStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            inStream.close();
        } catch (Exception ex) {
            throw new BusinessException(ex.getMessage(), true);
        }
    }

    /**
     * @param paraMap
     * @return
     * @description:
     * @author: sunxl
     * @date: 2020-05-26
     * @modify:
     */
    @PostMapping(value = "/exportTaskLogPersonExcel")
    public void exportExcelPerson(
            @RequestBody(required = false) Map<String, Object> paraMap,
            HttpServletRequest request, HttpServletResponse response) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
            String sord = ConvertUtil.convertToString(paraMap.get("sord"));
            String cols = ConvertUtil.convertToString(paraMap.get("cols"));
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(spellListSqlStatistics(paraMap));
            // modify by wushenghong  导出数据与查询数据不对应问题解决
            sql.appendSingle(" and state = 9 ");
            sql.appendSingle(" GROUP BY usercode,username,projectid ");
            if (!StringUtil.isEmpty(sidx) && !StringUtil.isEmpty(sord)) {
                sql.appendSingle(" order by {0} {1} ", sidx, sord);
            }
            List<Map<String, Object>> listDataMap = this.service
                    .queryMapByWhereStatistics(sql.toString(),
                            "queryMapByWherePerson");
            for (int i = 0; i < listDataMap.size(); i++) {
                Map<String, Object> groupInfoList = listDataMap.get(i);
                if (groupInfoList != null) {
                    groupInfoList.put("usercode",
                            listDataMap.get(i).get("usercode").toString());
                    groupInfoList.put("projectid",
                            listDataMap.get(i).get("projectid").toString());
                }
            }
            String[] colArray = cols.split(",");
            InputStream inStream = OfficeOperateUtil
                    .exportExeclXlsx(listDataMap, colArray);
            String fileName = "导出数据.xlsx";
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + fileName);
            response.setHeader("FileName",
                    URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "FileName");
            OutputStream outStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while ((len = inStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            inStream.close();
        } catch (Exception ex) {
            throw new BusinessException(ex.getMessage(), true);
        }
    }

    /**
     * @param paraMap
     * @return
     * @description:查询项目人员工作以及计划列表
     * @author: sunxl
     * @date:
     * @modify:
     */
    @GetMapping(value = "/projectForPersonStatistics")
    public ResponseResult<Object> projectForPersonStatistics(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            // 解析请求参数到map
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            // 处理分页和排序信息
            Query query = new Query(paraMap);
            // 存放最终结果
            List<Map<String, Object>> resultList = new ArrayList<>();
            // 获取项目日历
            List<Map<String, Object>> calendarList = queryCalendarFromDate(paraMap);
            // 获取日历存入结果集
            for (int i = 0; i < calendarList.size(); i++) {
                Map<String, Object> items = calendarList.get(i);
                if (items != null) {
                    Map<String, Object> dataMap = new HashMap<>();
                    dataMap.put("calendardate", items.get("calendardate"));
                    dataMap.put("weekofday", items.get("description"));
                    dataMap.put("calendartype", items.get("calendartype"));
                    // 人员和工作信息
                    List<Map<String, Object>> userProjectList = new ArrayList<>();
                    dataMap.put("userProjectList", userProjectList);
                    resultList.add(dataMap);
                }
            }

            // 获取数据总数量
            int totalCount = queryCalendarCount(paraMap);
            if (totalCount > 0) {
                // 获取项目人员列表
                List<Map<String, Object>> teamList = queryTeamForProject(
                        paraMap);
                // 存入结果集
                for (int i = 0; i < resultList.size(); i++) {
                    Map<String, Object> items = resultList.get(i);
                    if (items != null) {
                        List<Map<String, Object>> array = (List<Map<String, Object>>) items
                                .get("userProjectList");
                        for (int j = 0; j < teamList.size(); j++) {
                            Map<String, Object> userInfo = teamList.get(j);
                            if (userInfo != null) {
                                Map<String, Object> tmMap = new HashMap<>();

                                tmMap.put("username",
                                        userInfo.get("username").toString());
                                tmMap.put("usercode",
                                        userInfo.get("usercode").toString());
                                tmMap.put("icon", "");
                                array.add(tmMap);
                            }
                        }
                    }
                }

                if (teamList.size() > 0) {
                    // 获取任务日志列表
                    paraMap.put("sidx", "finishtime");
                    List<Map<String, Object>> taskLogList = queryTaskLogForProjectAndDate(
                            paraMap);
                    // 根据日期和人员筛选结果
                    for (int i = 0; i < taskLogList.size(); i++) {
                        Map<String, Object> items = taskLogList.get(i);
                        if (items != null) {
                            Map<String, Object> tt = getDestUserInfoFromDate(
                                    resultList, items);
                            if (tt != null) {
                                if ("9".equals(ConvertUtil.convertToString(items.get("state")))) {
                                    tt.put("icon",
                                            "/static/images/finishedtask.png");
                                } else {
                                    tt.put("icon",
                                            "/static/images/notReviewed.png");
                                }
//                                tt.put("icon",
//                                        "/static/images/finishedtask.png");
                            }
                        }
                    }

                    paraMap.put("sidx", "starttime");
                    // 获取任务列表
                    List<Map<String, Object>> taskList = queryTaskProjectAndDate(
                            paraMap);
                    // 更新计划图标
                    for (int i = 0; i < taskList.size(); i++) {
                        Map<String, Object> items = taskList.get(i);
                        if (items != null) {
                            updatePlanTask(resultList, items);
                        }
                    }
                }
            }

            Page page = new Page(resultList, totalCount, query.getPageSize(),
                    query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception ex) {
            ex.printStackTrace();
            return handleControllerException(ex);
        }
    }

    private void updatePlanTask(List<Map<String, Object>> resultList,
                                Map<String, Object> item) {
        for (int j = 0; j < resultList.size(); j++) {
            Map<String, Object> rl = resultList.get(j);
            if (rl != null) {
                Date cal = (Date) rl.get("calendardate");
                Date startDate = (Date) item.get("starttime");
                Date endDate = (Date) item.get("endtime");
                if (cal.compareTo(startDate) >= 0
                        && cal.compareTo(endDate) <= 0) {
                    List<Map<String, Object>> array = (List<Map<String, Object>>) rl
                            .get("userProjectList");
                    for (int i = 0; i < array.size(); i++) {
                        Map<String, Object> userInfo = array.get(i);
                        if (userInfo != null
                                && userInfo.get("icon").toString().isEmpty()) {
                            String dUserCode = userInfo.get("usercode").toString();
                            //如果是周末或者国家法定节假日 modify by wushenghong
                            if ((CboSystemConst.CboWorkingCalendarCategoryEnum.Weekend.equals(ConvertUtil.convertToString(rl.get("calendartype"))))
                                    || (CboSystemConst.CboWorkingCalendarCategoryEnum.Holidays.equals(ConvertUtil.convertToString(rl.get("calendartype"))))) {
                                userInfo.put("icon", "/static/images/restDay.png");
                            } else if (dUserCode.equals(item.get("leadercode").toString())) {
                                userInfo.put("icon",
                                        "/static/images/plantask.png");
                            } else {
                                // modify by wushenghong 判断参与人为空的情况
                                if (item.get("participantcodes") != null) {
                                    String ucs = item.get("participantcodes").toString();
                                    if (ucs != null) {
                                        if (ucs.indexOf(dUserCode) >= 0) {
                                            userInfo.put("icon",
                                                    "/static/images/plantask.png");
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    // modify by wushenghong  增加周末或法定假节日图标
                    List<Map<String, Object>> array = (List<Map<String, Object>>) rl
                            .get("userProjectList");
                    for (int i = 0; i < array.size(); i++) {

                        Map<String, Object> userInfo = array.get(i);
                        if (userInfo != null
                                && userInfo.get("icon").toString().isEmpty()) {
                            String dUserCode = userInfo.get("usercode").toString();
                            //如果是周末或者国家法定节假日
                            if ((CboSystemConst.CboWorkingCalendarCategoryEnum.Weekend.equals(ConvertUtil.convertToString(rl.get("calendartype"))))
                                    || (CboSystemConst.CboWorkingCalendarCategoryEnum.Holidays.equals(ConvertUtil.convertToString(rl.get("calendartype"))))) {
                                userInfo.put("icon", "/static/images/restDay.png");
                            }
                        }
                    }
                }
            }
        }
    }

    private Map<String, Object> getDestUserInfoFromDate(
            List<Map<String, Object>> resultList, Map<String, Object> item) {
        for (int j = 0; j < resultList.size(); j++) {
            Map<String, Object> rl = resultList.get(j);
            if (rl != null) {
                Date cal = (Date) rl.get("calendardate");
                Date finished = (Date) item.get("finishtime");
                if (cal.compareTo(finished) == 0) {
                    List<Map<String, Object>> array = (List<Map<String, Object>>) rl
                            .get("userProjectList");
                    for (int i = 0; i < array.size(); i++) {
                        Map<String, Object> userInfo = array.get(i);
                        if (userInfo != null) {
                            if (item.get("usercode").toString().equals(
                                    userInfo.get("usercode").toString())) {
                                return userInfo;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    private int queryCalendarCount(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled=1 ");
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and projectid={0}", value);
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and calendardate >= {0} ",
                        SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and calendardate <= {0}",
                        SQLAdapter.toDateLong(value + " 23:59:59"));
        }

        // 获取项目日历
        PmCalendarService pmCalendarService = (PmCalendarService) SpringUtil
                .getBean("pmCalendarService");
        return pmCalendarService.getCount(sql.toString());
    }

    private List<Map<String, Object>> queryCalendarFromDate(
            Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled=1 ");
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and projectid={0}", value);
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and calendardate >= {0} ",
                        SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and calendardate <= {0}",
                        SQLAdapter.toDateLong(value + " 23:59:59"));
        }

        // 获取项目日历
        Query query = new Query(paraMap);
        PmCalendarService pmCalendarService = (PmCalendarService) SpringUtil
                .getBean("pmCalendarService");
        List<Map<String, Object>> calendarList = null;
        if (query.getPageSize() > 0) {
            calendarList = pmCalendarService.queryMapForPage(sql.toString(),
                    query.getCurrentPage(), query.getPageSize(),
                    query.getSidx(), query.getSord());
        } else
            calendarList = pmCalendarService.queryMapByWhere(sql.toString());

        return calendarList;
    }

    private List<Map<String, Object>> queryTeamForProject(
            Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled=1 ");
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and projectid={0}", value);
        }

        PmTaskService pmTaskService = (PmTaskService) SpringUtil
                .getBean("pmTaskService");
        List<Map<String, Object>> taskList = pmTaskService
                .queryMapByWhere(sql.toString());

        List<Map<String, Object>> teamLst = new ArrayList<>();
        List<Map<String, Object>> rltLst = new ArrayList<>();
        for (int i = 0; i < taskList.size(); i++) {
            Map<String, Object> items = taskList.get(i);
            if (items != null) {
                Map<String, Object> tmMap = new HashMap<>();
                tmMap.put("username", items.get("leadername").toString());
                tmMap.put("usercode", items.get("leadercode").toString());
                teamLst.add(tmMap);
                // modify by wushenghong
                if (items.get("participantcodes") != null) {
                    String[] codes = items.get("participantcodes").toString()
                            .split(",");
                    String[] names = items.get("participantnames").toString()
                            .split(",");
                    for (int j = 0; j < codes.length; ++j) {
                        Map<String, Object> tmCMap = new HashMap<>();
                        tmCMap.put("username", names[j].toString());
                        tmCMap.put("usercode", codes[j].toString());
                        teamLst.add(tmCMap);
                    }
                }
            }
        }

        Set<String> set = new HashSet<>();
        for (Map<String, Object> item : teamLst) {
            String id = item.get("usercode").toString();
            if (!set.contains(id)) {
                Map<String, Object> tmRMap = new HashMap<>();
                tmRMap.put("username", item.get("username").toString());
                tmRMap.put("usercode", item.get("usercode").toString());
                rltLst.add(tmRMap);
            }
            set.add(id);
        }

        return rltLst;
    }

    private List<Map<String, Object>> queryTaskLogForProjectAndDate(
            Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled=1 ");
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and projectid={0}", value);
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and finishtime >= {0} ",
                        SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and finishtime <= {0}",
                        SQLAdapter.toDateLong(value + " 23:59:59"));
        }

        // Query query = new Query(paraMap);
        List<Map<String, Object>> taskLogList = null;
        // if (query.getPageSize() > 0)
        // {
        // taskLogList = this.service.queryMapForPage(sql.toString(),
        // query.getCurrentPage(), query.getPageSize(),
        // query.getSidx(), query.getSord());
        // }
        // else
        taskLogList = this.service.queryMapByWhere(sql.toString());
        return taskLogList;
    }

    private List<Map<String, Object>> queryTaskProjectAndDate(
            Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled=1 ");
        if (paraMap.containsKey("qry_projectid")) {
            String value = paraMap.get("qry_projectid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and projectid={0}", value);
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and starttime <= {0} ",
                        SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and endtime >= {0}",
                        SQLAdapter.toDateLong(value + " 23:59:59"));
        }

        PmTaskService pmTaskService = (PmTaskService) SpringUtil
                .getBean("pmTaskService");
        // Query query = new Query(paraMap);
        List<Map<String, Object>> taskList = null;
        // if (query.getPageSize() > 0)
        // {
        // taskList = pmTaskService.queryMapForPage(sql.toString(),
        // query.getCurrentPage(), query.getPageSize(),
        // query.getSidx(), query.getSord());
        // }
        // else
        taskList = pmTaskService.queryMapByWhere(sql.toString());
        return taskList;
    }

    /**
     * @return
     * @description: 人员工作量及计划
     * @author: shenyouyi
     * @date: 2020-06-04
     * @modify:
     */
    @GetMapping(value = "/personWorkloadAndPlanStatistics")
    public ResponseResult<Object> personWorkloadAndPlanList(
            @RequestParam(required = false) Map<String, Object> paraMap) {
        paraMap = BaseUtil.decodeSecureMap(paraMap);
        // 一天一条记录
        String qry_begindate = ConvertUtil
                .convertToString(paraMap.get("qry_begindate"));
        Date begindate = DateUtil.stringToDate(qry_begindate);
        String qry_enddate = ConvertUtil
                .convertToString(paraMap.get("qry_enddate"));
        Date enddate = DateUtil.stringToDate(qry_enddate);
        Long totalCount = cn.hutool.core.date.DateUtil.betweenDay(begindate,
                enddate, false) + 1;
        Date todayZeroTime = DateUtil.getZreoOfDay(new Date());
        Query query = new Query(paraMap);
        String qry_usercodes = ConvertUtil
                .convertToString(paraMap.get("qry_usercodes"));
        String[] usercodeArray = qry_usercodes.split(",");
        List<String> usercodeList = Arrays.stream(usercodeArray)
                .map(usercode -> "'" + usercode + "'")
                .collect(Collectors.toList());
        String usercodeWhere = String.join(",", usercodeList);
        List<Map<String, Object>> resultList = null;
        if (enddate.before(todayZeroTime)) { // 所有的都查询工作日志
            List<PmTaskLogEntity> pmTaskLogList = queryTaskLogByUserAndDate(
                    usercodeWhere, qry_begindate, qry_enddate);
            resultList = dealPmTaskLog(pmTaskLogList, totalCount, begindate,
                    usercodeArray);
        } else if (begindate.after(todayZeroTime)
                || begindate.equals(todayZeroTime)) {// 所有的都查询计划
            List<PmTaskEntity> pmTaskList = queryTaskByUserAndDate(
                    usercodeWhere, usercodeArray, qry_begindate, qry_enddate);
            resultList = dealPmTask(pmTaskList, totalCount, begindate,
                    usercodeArray);
        } else { // begindate ~ yesterday 查工作日志，todayZeroTime ~ enddate 查计划
            Date yesterday = DateUtil.addDate(todayZeroTime, -1,
                    Calendar.DAY_OF_YEAR);
            List<PmTaskLogEntity> pmTaskLogList = queryTaskLogByUserAndDate(
                    usercodeWhere, qry_begindate,
                    DateUtil.dateToString(yesterday, "yyyy-MM-dd"));
            Long taskLogCount = cn.hutool.core.date.DateUtil
                    .betweenDay(begindate, yesterday, false) + 1;
            resultList = dealPmTaskLog(pmTaskLogList, taskLogCount, begindate,
                    usercodeArray);
            List<PmTaskEntity> pmTaskList = queryTaskByUserAndDate(
                    usercodeWhere, usercodeArray,
                    DateUtil.dateToString(todayZeroTime, "yyyy-MM-dd"),
                    qry_enddate);
            Long taskCount = cn.hutool.core.date.DateUtil
                    .betweenDay(todayZeroTime, enddate, false) + 1;
            List<Map<String, Object>> partResultList = dealPmTask(pmTaskList,
                    taskCount, todayZeroTime, usercodeArray);
            resultList.addAll(partResultList);
        }
        // 重新组织数据
        Page page = new Page(resultList, totalCount.intValue(),
                query.getPageSize(), query.getCurrentPage());
        return ResponseResult.ok(page);
    }

    /**
     * @param pmTaskList
     * @param totalCount
     * @param begindate
     * @param usercodeArray
     * @return
     * @description: 将查询出来的项目任务组装成结果记录
     */
    private List<Map<String, Object>> dealPmTask(List<PmTaskEntity> pmTaskList,
                                                 Long totalCount, Date begindate, String[] usercodeArray) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (int i = 0; i < totalCount; i++) {
            Map<String, Object> dataMap = new HashMap<>();
            Date operatedate = DateUtil.addDate(begindate, i,
                    Calendar.DAY_OF_YEAR);
            dataMap.put("operatedate", operatedate);
            List<Map<String, Object>> userProjectList = new ArrayList<>();
            for (String usercode : usercodeArray) {
                Map<String, Object> userProjectMap = new HashMap<>();
                // 找出当前用户当前日期计划参与的项目
                List<Long> projectidList = pmTaskList.stream().filter(
                        pmTask -> !pmTask.getStarttime().after(operatedate)
                                && !pmTask.getEndtime().before(operatedate)
                                && (pmTask.getLeadercode().equals(usercode)
                                || Arrays
                                .asList(ConvertUtil.convertToString(pmTask.getParticipantcodes())
                                        .split(","))
                                .contains(usercode)))
                        .map(PmTaskEntity::getProjectid)
                        .collect(Collectors.toList());
                if (projectidList.size() > 0) {
                    List<String> projectIdList = projectidList.stream()
                            .map(projectid -> projectid.toString())
                            .collect(Collectors.toList());
                    PmProjectService pmProjectService = (PmProjectService) SpringUtil
                            .getBean("pmProjectService");
                    List<PmProjectEntity> projectList = pmProjectService
                            .queryByIds(String.join(",", projectIdList));
                    List<String> docnoList = projectList.stream()
                            .map(PmProjectEntity::getDocno)
                            .collect(Collectors.toList());
                    userProjectMap.put("projectcodes",
                            String.join(",", docnoList));
                    List<String> projectnameList = projectList.stream()
                            .map(PmProjectEntity::getName)
                            .collect(Collectors.toList());
                    userProjectMap.put("projectnames",
                            String.join(",", projectnameList));
                } else {
                    userProjectMap.put("projectcodes", "");
                    userProjectMap.put("projectnames", "");
                }
                userProjectList.add(userProjectMap);
            }
            dataMap.put("userProjectList", userProjectList);
            resultList.add(dataMap);
        }
        return resultList;
    }

    /**
     * @param pmTaskLogList
     * @param totalCount
     * @param begindate
     * @param usercodeArray
     * @return
     * @description: 将查询出来的项目日志组装成结果记录
     */
    private List<Map<String, Object>> dealPmTaskLog(
            List<PmTaskLogEntity> pmTaskLogList, Long totalCount,
            Date begindate, String[] usercodeArray) {
        // 1. 先根据日期分组
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<Date, List<PmTaskLogEntity>> pmTaskLogDateMap = pmTaskLogList
                .stream()
                .collect(Collectors.groupingBy(PmTaskLogEntity::getFinishtime));
        for (int i = 0; i < totalCount; i++) {
            // 2.获取当前天的工作日志
            Map<String, Object> dataMap = new HashMap<>();
            Date operatedate = DateUtil.addDate(begindate, i,
                    Calendar.DAY_OF_YEAR);
            dataMap.put("operatedate", operatedate);
            List<Map<String, Object>> userProjectList = new ArrayList<>();
            List<PmTaskLogEntity> pmTaskLogOfOperatedate = pmTaskLogDateMap
                    .get(operatedate);
            // 3.将工作日志根据人员来分配
            for (String usercode : usercodeArray) {
                Map<String, Object> userProjectMap = new HashMap<>();
                List<PmTaskLogEntity> pmTaskLogOfUser = pmTaskLogOfOperatedate != null
                        ? pmTaskLogOfOperatedate.stream()
                        .filter(pmTaskLog -> usercode
                                .equals(pmTaskLog.getUsercode()))
                        .collect(Collectors.toList())
                        : new ArrayList<>();
                if (pmTaskLogOfUser.size() > 0) {
                    List<Long> projectidList = pmTaskLogOfUser.stream()
                            .map(PmTaskLogEntity::getProjectid)
                            .collect(Collectors.toList());
                    if (projectidList.size() > 0) {
                        List<String> projectIdList = projectidList.stream()
                                .map(projectid -> projectid.toString())
                                .collect(Collectors.toList());
                        PmProjectService pmProjectService = (PmProjectService) SpringUtil
                                .getBean("pmProjectService");
                        List<PmProjectEntity> projectList = pmProjectService
                                .queryByIds(String.join(",", projectIdList));
                        List<String> docnoList = projectList.stream()
                                .map(PmProjectEntity::getDocno)
                                .collect(Collectors.toList());
                        userProjectMap.put("projectcodes",
                                String.join(",", docnoList));
                        List<String> projectnameList = projectList.stream()
                                .map(PmProjectEntity::getName)
                                .collect(Collectors.toList());
                        userProjectMap.put("projectnames",
                                String.join(",", projectnameList));
                    } else {
                        userProjectMap.put("projectcodes", "");
                        userProjectMap.put("projectnames", "");
                    }
                } else {
                    userProjectMap.put("projectcodes", "");
                    userProjectMap.put("projectnames", "");
                }
                userProjectList.add(userProjectMap);
            }
            dataMap.put("userProjectList", userProjectList);
            resultList.add(dataMap);
        }
        return resultList;
    }

    /**
     * @param usercodeWhere
     * @param qry_begindate
     * @param qry_enddate
     * @return
     * @description: 根据人员和日期查询工作日志
     * @author: shenyouyi
     */
    private List<PmTaskLogEntity> queryTaskLogByUserAndDate(
            String usercodeWhere, String qry_begindate, String qry_enddate) {
        StringBufferProxy sqlWhere = new StringBufferProxy();
        sqlWhere.appendSingle("usercode in ({0})", usercodeWhere);
        sqlWhere.appendSingle(" and finishtime >= {0} and finishtime <= {1}",
                SQLAdapter.toDateLong(qry_begindate),
                SQLAdapter.toDateLong(qry_enddate));
        List<PmTaskLogEntity> pmTaskLogList = this.service
                .queryByWhere(sqlWhere.toString());
        return pmTaskLogList;
    }

    /**
     * @param usercodeWhere
     * @param qry_begindate
     * @param qry_enddate
     * @return
     * @description: 根据人员和日期查询项目任务
     * @author: shenyouyi
     */
    private List<PmTaskEntity> queryTaskByUserAndDate(String usercodeWhere,
                                                      String[] usercodeArray, String qry_begindate, String qry_enddate) {
        StringBufferProxy sqlWhere = new StringBufferProxy();
        // 判断工号
        sqlWhere.appendSingle("state != 2 and state != 0 and (leadercode in ({0}) ", usercodeWhere);
        for (String usercode : usercodeArray) {
            sqlWhere.appendSingle("or participantcodes like '%{0}%' ",
                    usercode);
        }
        // 判断两个日期是否重叠
        sqlWhere.appendSingle(") and (starttime <= {0} and endtime >= {1})",
                SQLAdapter.toDateLong(qry_enddate),
                SQLAdapter.toDateLong(qry_begindate));
        PmTaskService pmTaskService = (PmTaskService) SpringUtil
                .getBean("pmTaskService");
        List<PmTaskEntity> pmTaskList = pmTaskService
                .queryByWhere(sqlWhere.toString());
        return pmTaskList;
    }

    @Override
    @PostMapping({"/exportBigExcel"})
    public ResponseResult<Object> exportBigExcel(@RequestBody(required = false)Map<String, Object> paraMap,
        HttpServletRequest request, HttpServletResponse response) {
        paraMap = BaseUtil.decodeSecureMap(paraMap);
        String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
        String sord = ConvertUtil.convertToString(paraMap.get("sord"));
        String cols = ConvertUtil.convertToString(paraMap.get("cols"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(this.spellListSqlStatistics(paraMap), new Object[0]);
        Map<String, String> queryMap = new HashMap();
        queryMap.put("sqlwhere", sql.toString());
        queryMap.put("sidx", sidx);
        queryMap.put("sord", sord);
        String fileName = ConvertUtil.convertToString(paraMap.get("fileName"));
        fileName = fileName.length() == 0 ? "导出数据.xlsx" : fileName + ".xlsx";

        try {
            OfficeOperateUtil.exportExcelXlsx(response, (ITapService)this.service, queryMap, "", fileName, cols, this.getUserBean().getUser().getId());
            return null;
        } catch (Exception var11) {
            return this.handleControllerException(var11);
        }
    }

    @Override
    @GetMapping({"/list"})
    public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSql(paraMap);
            paraMap.put("whereSql",sqlWhere);
            int totalCount = this.service.getCount(paraMap,"getTaskLogAndProjectCount");
            List<Map<String, Object>> tempList = null;
            HashMap<String, Object> paraMap2 = new HashMap<>();
            paraMap2.put("curPageIndex",query.getCurrentPage());
            int beginCount=query.getCurrentPage()*query.getPageSize()-query.getPageSize();
            paraMap2.put("begincount",beginCount);
            paraMap2.put("pagesize", query.getPageSize());
            paraMap2.put("sidx", query.getSidx());
            paraMap2.put("sord", query.getSord());
            paraMap2.put("whereSql", sqlWhere);
            if (query.getPageSize() > 0) {
                tempList = this.service.queryMapForPage(paraMap2,"getTaskLogAndProject");
            } else {
                tempList = this.service.queryMap(paraMap2,"queryMapByWhere1");
            }
            this.service.setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }


}
